﻿using LeoK.TM.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LeoK.Common;
using Telerik.Windows.Controls;

namespace LeoK.TM
{
    /// <summary>
    /// SlnManager.xaml 的交互逻辑
    /// </summary>
    public partial class SlnManager : UserControl
    {
        private LeoKDataGrid<TM_Sln> _leoKDataGrid;

        public SlnManager()
        {
            InitializeComponent();

            _leoKDataGrid = new LeoKDataGrid<TM_Sln>();
            layout.Children.Add(_leoKDataGrid);

            _leoKDataGrid.BeforeGeneratingColumn = BeforeGeneratingColumn;

            Loaded += (sender, args) =>
            {
                LoadData();
            };
        }

        private bool BeforeGeneratingColumn(GridViewAutoGeneratingColumnEventArgs e)
        {
            bool result = false;

            if (e.Column.UniqueName == "ColorFlag")
            {
                ColorPickerColumn col = new ColorPickerColumn();
                col.UniqueName = "ColorFlag";
                col.Header = "标志颜色";

                e.Column = col;
                result = true;
            }

            return result;
        }

        public void LoadData()
        {
            _leoKDataGrid.LoadData();
        }

        private void btnRefresh_Click(object sender, MouseButtonEventArgs e)
        {
            LoadData();
        }

        private async void btnCalc_Click(object sender, MouseButtonEventArgs e)
        {
            using (MySqlDB db = new MySqlDB())
            {
                string updateSql = @"UPDATE TM_Sln A INNER JOIN
                                    (
	                                    SELECT SlnID, SUM(TimeSpend) AS Total FROM TM_Task GROUP BY SlnID  
                                    ) AS C ON A.ID=C.SlnID
                                    SET A.TimeSpend=C.Total,A.Cost=C.Total,A.UpdateTime=now()
                                    WHERE A.TimeSpend<>C.Total";
                await db.ExecuteNonQuery(updateSql, null);
            }
            
            LoadData();
        }
    }
}
